package com.hundsun.yr.universal.p2p.ui.activity;

import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.widget.ImageView;

import com.hundsun.mobile.zwgt.R;
import com.hundsun.yr.universal.library.data.HSSharedPreferences;
import com.hundsun.yr.universal.library.eventbus.EventCenter;
import com.hundsun.yr.universal.library.netstatus.NetUtils.NetType;
import com.hundsun.yr.universal.library.utils.ThemeUtils;
import com.hundsun.yr.universal.p2p.bean.AliasTagBean;
import com.hundsun.yr.universal.p2p.bean.UserInfo;
import com.hundsun.yr.universal.p2p.config.Config;
import com.hundsun.yr.universal.p2p.config.Constants;
import com.hundsun.yr.universal.p2p.config.Extras;
import com.hundsun.yr.universal.p2p.config.TaskConstants;
import com.hundsun.yr.universal.p2p.presenter.base.RequestPresenter;
import com.hundsun.yr.universal.p2p.presenter.base.SplashPresenter;
import com.hundsun.yr.universal.p2p.presenter.impl.InitializePresenterImpl;
import com.hundsun.yr.universal.p2p.presenter.impl.SplashPresenterImpl;
import com.hundsun.yr.universal.p2p.ui.activity.base.BaseActivity;
import com.hundsun.yr.universal.p2p.utils.BaseRequestTool2;
import com.hundsun.yr.universal.p2p.utils.CommTool;
import com.hundsun.yr.universal.p2p.utils.LocationUtils;
import com.hundsun.yr.universal.p2p.utils.Logs;
import com.hundsun.yr.universal.p2p.view.SplashView;
import com.hundsun.yr.universal.p2p.view.base.InitializeView;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.jpush.android.api.JPushInterface;
import de.greenrobot.event.EventBus;

/**
 *  启动页页面
 */
public class SplashActivity extends BaseActivity implements SplashView, InitializeView {

    private static final int REQUEST_PERMISSION = 0;


    private ImageView mSplashImage;
    //	private TextView mVersionName;
//	private TextView mCopyright;
    private SplashPresenter mSplashPresenter = null;
    private RequestPresenter mPresenter2;
    private LocationUtils locationUtils;

    //    private ProtocolNameHandler mDataHandler;
//    private Class userPushService = DemoPushService.class;
    private String zwgt_data;
    private HSSharedPreferences mHsSharedPreferences = null;

    private ImageView iv_icon_type = null;


    @Override
    protected int getContentViewLayoutID() {
        return R.layout.act_splash;
    }


    @Override
    public void animateBackgroundImage(Animation animation) {
        mSplashImage.startAnimation(animation);
//		navigateToHomePage(false);
    }


    @Override
    public void initializeViews(String versionName, String copyright,
                                int backgroundResId) {
//		mCopyright.setText(copyright);
//        mVersionName.setText(versionName);
//        if (!CommTool.getChannel(mContext).equals("P1OJDiTB")){
//            changeIcon("com.hundsun.mobile.zwgt.other_launch");
//        } else {
//            changeIcon("com.hundsun.yr.universal.p2p.ui.activity.SplashActivity");
//        }

        mSplashImage.setImageResource(backgroundResId);

        iv_icon_type = findView(R.id.iv_icon_type);

        if (CommTool.getChannel(mContext).contains("kBRo9kNQ")){
            iv_icon_type.setImageResource(R.drawable.icon_360);
        }

//        // SDK初始化，第三方程序启动时，都要进行SDK初始化工作
//        PackageManager pkgManager = getPackageManager();
//        // 读写 sd card 权限非常重要, android6.0默认禁止的, 建议初始化之前就弹窗让用户赋予该权限
//        boolean sdCardWritePermission =
//                pkgManager.checkPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE, getPackageName()) == PackageManager.PERMISSION_GRANTED;
//
//        // read phone state用于获取 imei 设备信息
//        boolean phoneSatePermission =
//                pkgManager.checkPermission(Manifest.permission.READ_PHONE_STATE, getPackageName()) == PackageManager.PERMISSION_GRANTED;
//
//        if (Build.VERSION.SDK_INT >= 23 && !sdCardWritePermission || !phoneSatePermission) {
//            requestPermission();
//        } else {
//            // SDK初始化，第三方程序启动时，都要进行SDK初始化工作
//            initPush();
//        }

    }

    /**
     * 自动登陆
     */
    private void automaticLogin() {
        if (sharedPreferences.getShareProf(UserInfo.TOKENID) != null && !sharedPreferences.getShareProf(UserInfo.TOKENID).isEmpty()) {
            zwgt_data = BaseRequestTool2.getFormatedDateString();
            JSONObject map = new JSONObject();
            try {
                map.put("token", sharedPreferences.getShareProf(UserInfo.TOKENID));
            } catch (JSONException e) {
                e.printStackTrace();
            }

            JSONObject jsonParams = CommTool.getJSONParams(map, sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), zwgt_data);
            mPresenter2.loadingData(TaskConstants.TASK_LOGINSILENT, mContext.getString(R.string.root_url_test) + mContext.getString(R.string.api_index_test)
                    + TaskConstants.TASK_LOGINSILENT, Constants.EVENT_DATA, jsonParams, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_POST, mContext.getString(R.string.api_index_test)
                    + TaskConstants.TASK_LOGINSILENT, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), true);
        }
    }

    public static String replaceBlank(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

    @Override
    public void navigateToHomePage(boolean islogin) {
        String versionName = "";
        try {
            versionName = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
        } catch (Exception e) {
            Logs.e(e.getMessage());
        }
        if (!mHsSharedPreferences.getBoolean(Config.IF_GOGUIDE) /*|| !TextUtils.equals(mHsSharedPreferences.getShareProf(Config.VERSION_NAME), versionName)*/) {
            mHsSharedPreferences.putShareProf(Config.VERSION_NAME, versionName);
            readyGoThenKill(GuideActivity.class);

        } else {
            Bundle bundle = new Bundle();
            bundle.putString(Extras.NAVIGATE_TAG, "HOME");
            if (islogin) readyGoThenKill(MainActivity.class);
            else readyGoThenKill(MainActivity.class, bundle);
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected boolean isApplyKitKatTranslucency() {
        return false;
    }


    @Override
    protected void getBundleExtras(Bundle extras) {

    }


    @SuppressWarnings("rawtypes")
    @Override
    protected void onEveComming(EventCenter eventCenter) {
    }


    @Override
    protected View getLoadingTargetView() {
        return null;
    }


    @Override
    protected void initViewsAndEvents() {
        //问题：某些机安装的时候常见两个launch  MainActivity
        ThemeUtils.setTheme(R.style.AppTheme_LightBlue, R.color.primary_cl);
        mHsSharedPreferences = new HSSharedPreferences(mContext, Config.SPPath.file_configInfo);
        mSplashImage = (ImageView) findViewById(R.id.splash_image);
        mSplashPresenter = new SplashPresenterImpl(this, this);
        mSplashPresenter.initialized();
        mSplashPresenter.config();
        //打开mainActivity并且处于登陆的时候，自动登录一次
        mPresenter2 = new InitializePresenterImpl(mContext, this);

        if (sharedPreferences.getBoolean(UserInfo.ISLOGIN)) {
            automaticLogin();
            setTagAndAlies();
        }
    }


    @Override
    protected void onNetworkConnected(NetType type) {

    }


    @Override
    protected void onNetworkDisConnected() {

    }


    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return true;
    }


    @Override
    protected boolean isBindEventBusHere() {
        return false;
    }


    @Override
    protected boolean toggleOverridePendingTransition() {
        return false;
    }


    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        return null;
    }


//    private void requestPermission() {
//        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE},
//                REQUEST_PERMISSION);
//    }

//    @Override
//    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
//        if (requestCode == REQUEST_PERMISSION) {
//            if ((grantResults.length == 2 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED)) {
////                PushManager.getInstance().initialize(this.getApplicationContext(), userPushService);
//            } else {
//                Log.e("GetuiSdkDemo",
//                        "we highly recommend that you need to grant the special permissions before initializing the SDK, otherwise some "
//                                + "functions will not work");
//                initPush();
//            }
//        } else {
//            onRequestPermissionsResult(requestCode, permissions, grantResults);
//        }
//    }


    /**
     * 开启推送
     */
    private void initPush() {
//        PushManager.getInstance().initialize(this.getApplicationContext(), userPushService);
    }

    @Override
    public <T> void initializeViews(String task_name, T data) {
        // TODO Auto-generated method stub
        switch (task_name) {
            case TaskConstants.TASK_LOGINSILENT:
                EventBus.getDefault().post(new EventCenter(Constants.EVENT_REFRESH_DATA));//登陆成功通知某些页面进行数据刷新
                locationUtils = new LocationUtils(mContext);
                String latitude = locationUtils.getLatitude();
                String longitude = locationUtils.getLongitude();

                //将获取到的位置信息传送到服务端
                zwgt_data = BaseRequestTool2.getFormatedDateString();
                JSONObject map = new JSONObject();
                try {
                    map.put("lat", latitude);
                    map.put("lon", longitude);
                    Log.e("MY POSITION",latitude+"  "+longitude);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                JSONObject jsonParams = CommTool.getJSONParams(map, sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), zwgt_data);
                mPresenter2.loadingData(TaskConstants.TASK_LOCATION, mContext.getString(R.string.root_url_test) + mContext.getString(R.string.api_user_test)
                        + TaskConstants.TASK_LOCATION, Constants.EVENT_DATA, jsonParams, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_POST, mContext.getString(R.string.api_user_test)
                        + TaskConstants.TASK_LOCATION, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), false);
                break;
            case TaskConstants.TASK_LOCATION:
                locationUtils.removeLocationManagerListener();
                break;

            case TaskConstants.TASK_GETPUSHINFO:
                if (data != null) {
                    AliasTagBean aliasTagBean = (AliasTagBean) data;
                    JPushInterface.setAlias(this, 1, aliasTagBean.alias);
                    Set set = new HashSet();
                    set.addAll(aliasTagBean.tag);
                    JPushInterface.setTags(this, 1, set);
                }
                break;
        }
    }

    @Override
    public <T> void initializeError(String task_name, T data) {

    }

    public void setTagAndAlies(){
        if (sharedPreferences.getShareProf(UserInfo.TOKENID) != null && !sharedPreferences.getShareProf(UserInfo.TOKENID).isEmpty()) {
            zwgt_data = BaseRequestTool2.getFormatedDateString();
            JSONObject map = new JSONObject();
            try {
                map.put("a", "1");
            } catch (JSONException e) {
                e.printStackTrace();
            }

            JSONObject jsonParams = CommTool.getJSONParams(map, sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), zwgt_data);
            mPresenter2.loadingData(TaskConstants.TASK_GETPUSHINFO, mContext.getString(R.string.root_url_test) + mContext.getString(R.string.api_user_test)
                    + TaskConstants.TASK_GETPUSHINFO, Constants.EVENT_DATA, jsonParams, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_POST, mContext.getString(R.string.api_user_test)
                    + TaskConstants.TASK_GETPUSHINFO, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), true);
        }

    }

}
